﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TDB.DBInternals;
using TDB.Services;
using System.ServiceModel;

namespace TDB.Communication
{
  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  //ConcurrencyMode = ConcurrencyMode.Single,
  //TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable)]
  public class CommandService : ICommandService
  {
    [OperationBehavior(TransactionScopeRequired = true)]
    public void Set(string database, dynamic entity)
    {
      ServiceExtensions.Set(entity, database);
    }

    [OperationBehavior(TransactionScopeRequired = true)]
    public void SetCollection(string database, IEnumerable<dynamic> entities)
    {
      if (entities.Count() > 0)
      {
        Type entype = entities.FirstOrDefault().GetType();

        var mi = typeof(CommandService).GetMethod("SetCollectionGeneric", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        var gmi = mi.MakeGenericMethod(entype);
        gmi.Invoke(this, new object[] { database, entities });
      }
    }

    private void SetCollectionGeneric<T>(string database, IEnumerable<dynamic> entities)
    {
      List<T> ents = new List<T>();
      foreach (var d in entities)
        ents.Add((T)d);

      ents.SetCollection(database);
    }
  }
}
